#!/usr/bin/env python
import threading
import os
import sys
import time
import SimpleHTTPServer
import SocketServer
import subprocess

http_port = 8001


class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    allow_reuse_address = True


class WebServer:
    def __init__(self, port):
        self.port = port
    def __enter__(self):
        self.httpd = ThreadedTCPServer(('', self.port), SimpleHTTPServer.SimpleHTTPRequestHandler)
        self.httpd_thread = threading.Thread(target=self.httpd.serve_forever)
        self.httpd_thread.start()
        return self.httpd
    def __exit__(self, type, value, traceback):
        self.httpd.shutdown()


class TailLog(threading.Thread):
    def __init__(self, filename):
        super(TailLog, self).__init__()
        self.filename = filename
        self.file = None
    def __enter__(self):
        self.start()
    def __exit__(self, type, value, traceback):
        self.filename = None # signals thread to exit
        if self.file:
            self.file.close()
        self.join()
    def run(self):
        while True:
            filename = self.filename
            if not filename: break
            if not self.file:
                print 'open', filename
                try: self.file = open(filename, 'rt')
                except IOError: 
                    time.sleep(1.0) # files does not exist yet...
                if not self.filename: break # resolve race with __exit__
            if self.file:
                line = self.file.readline()
                if line: print '%s: %s'%(filename, line.rstrip())
                else: time.sleep(0.1)


def main():
    assert len(sys.argv)!=1, 'first argument should be the path to a chrome executable'

    chrome_cmd = [
        sys.argv[1],
        '--user-data-dir=%s'%os.path.join(os.getcwd(), '.chrome_userdata'),
        '--show-fps-counter',
        '--unlimited-quota-for-files',
        '--disable-web-security',
        '--enable-accelerated-plugins',
        '--enable-nacl',
        '--no-sandbox', 
        'http://127.0.0.1:%d/test.html'%http_port
    ]

#        '--disable-gpu-vsync',

    os.environ['NACL_ENABLE_PPAPI_DEV'] = '1'
    os.environ['NACL_PLUGIN_LOG'] = os.path.join(os.getcwd(), 'nacl.log')
    os.environ['NACL_EXE_STDOUT'] = os.path.join(os.getcwd(), 'stdout.log')
    os.environ['NACL_EXE_STDERR'] = os.path.join(os.getcwd(), 'stdout.log')

    #os.environ['PPAPI_BROWSER_DEBUG'] = '1'
    #os.environ['NACL_PPAPI_PROXY_DEBUG'] = '1'
    #os.environ['NACL_PLUGIN_DEBUG'] = '1'
    #os.environ['NACL_SRPC_DEBUG'] = '1'
    #os.environ['NACLVERBOSITY'] = '2' 
 
    for log in ('nacl.log', 'stdout.log'):
        try: os.unlink(log)
        except OSError: pass

    with WebServer(http_port), TailLog('stdout.log'):
        chrome = subprocess.call(chrome_cmd)

main()
